<template>
  <!-- 背景容器，占满整个屏幕 -->
  <div class="login-container" :style="{ backgroundImage: `url(${bgImg})` }">
    <div class="account-container">
      <el-form
        ref="ruleFormRef"
        style="max-width: 500px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="账号" prop="account" required>
          <el-input v-model="ruleForm.account" />
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-button id="logbtn" class="login-btn" type="primary" @click="hanleLogin()"
          >登录</el-button
        >
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import bgImg from '../assets/background.png'
import { login } from '@/js/my_fetch'
import router from '@/router'

// 表单引用
const ruleFormRef = ref()

// 响应式表单数据
const ruleForm = reactive({
  account: '',
  pass: '',
})

// 验证规则
const rules = reactive({
  account: [{ required: true, message: '请输入账号'}],
  pass: [{ required: true, message: '请输入密码' }],
})

const hanleLogin = async () => {
  if (!ruleFormRef.value) return

  try {
    console.log('我是' + JSON.stringify(ruleForm))
    const response = await login(ruleForm)
    if (!response.data || response.code !== 200) {
      throw new Error(response.msg) // 手动抛出错误，进入catch块
    }
    ElMessage.success('登录成功')
    router.push('/main')
  } catch (error) {
    ElMessage.error(error.message)
  }
}
</script>
<style scoped>
/* 确保页面占满全屏 */
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.login-btn {
  display: block; /* 将按钮转为块级元素，使其能响应margin水平居中 */
  margin: 20px auto 0; /* 上下间距20px，左右自动（居中） */
  width: 30%; /* 可选：让按钮宽度与输入框保持一致 */
}

/* 账号容器：仅需设置宽度和内边距等样式，无需flex布局 */
.account-container {
  width: 100%;
  max-width: 500px; /* 限制最大宽度，避免表单过宽 */
  padding: 20px;
  background: rgba(255, 255, 255, 0.9); /* 可选：添加背景色增强可读性 */
  border-radius: 8px; /* 可选：添加圆角 */
}

.login-container {
  /* 设置背景图片（替换为你的图片路径） */
  background-image: url('../assets/background.png');
  /* 图片铺满容器 */
  background-size: cover;
  /* 图片居中显示 */
  background-position: center;
  /* 背景固定不滚动 */
  background-attachment: fixed;
  /* 占满整个屏幕高度 */
  height: 100vh;
  width: 100%;
  /* 关键：设置为flex容器，使子元素居中 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
</style>
